package com.action.gulimall.search.service.impl;

import com.action.common.constant.SearchConstant;
import com.action.common.model.es.SkuEsModel;
import com.action.gulimall.search.config.RestClientConfig;
import com.action.gulimall.search.service.ProductService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @ClassName ProductServiceImpl
 * @Deacription 产品相关
 * @Author sl
 * @Date 2021/6/18/018 10:22
 * @Version 1.0
 **/
@Slf4j
@Service
public class ProductServiceImpl implements ProductService{

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public boolean saveSkuModels(List<SkuEsModel> skuEsModels) throws IOException {
        BulkRequest  bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(SearchConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            indexRequest.source(JSON.toJSONString(skuEsModel), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RestClientConfig.COMMON_OPTIONS);
        boolean hasError = bulkResponse.hasFailures();
        if(hasError){
            log.error("批量保存skuEsModel出现异常,异常结果:"+bulkResponse.buildFailureMessage());
        }
        return !hasError;
    }


}
